<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>校园二手交易平台</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        body {
            font-family: Arial, sans-serif;
            background-color: #f5f5f5;
        }
        .header {
            background: white;
            padding: 15px 0;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
            position: fixed;
            width: 100%;
            top: 0;
            z-index: 100;
        }
        .nav {
            max-width: 1200px;
            margin: 0 auto;
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 0 20px;
        }
        .logo {
            font-size: 24px;
            font-weight: bold;
            color: #333;
        }
        .search-bar {
            flex: 1;
            max-width: 400px;
            margin: 0 20px;
            display: flex;
        }
        .search-bar input {
            width: 100%;
            padding: 10px;
            border: 1px solid #ddd;
            border-radius: 5px 0 0 5px;
            outline: none;
        }
        .search-button {
            padding: 10px 15px;
            background: #4a89dc;
            color: white;
            border: none;
            border-radius: 0 5px 5px 0;
            cursor: pointer;
            transition: background 0.3s;
        }
        .search-button:hover {
            background: #3b7dd8;
        }
        .user-menu {
            display: flex;
            align-items: center;
            gap: 15px;
        }
        .user-avatar {
            width: 40px;
            height: 40px;
            border-radius: 50%;
            background: #667eea;
            display: flex;
            align-items: center;
            justify-content: center;
            color: white;
            cursor: pointer;
        }
        .sidebar {
            position: fixed;
            left: 0;
            top: 80px;
            width: 200px;
            height: calc(100vh - 80px);
            background: white;
            padding: 20px;
            box-shadow: 2px 0 4px rgba(0,0,0,0.1);
            z-index: 90;
        }
        .sidebar-menu {
            list-style: none;
        }
        .sidebar-menu li {
            margin-bottom: 15px;
        }
        .sidebar-menu a {
            text-decoration: none;
            color: #333;
            padding: 10px;
            display: block;
            border-radius: 5px;
            transition: background 0.3s;
        }
        .sidebar-menu a:hover {
            background: #f0f0f0;
        }
        .main-content {
            margin-left: 220px;
            margin-top: 80px;
            padding: 20px;
        }
        .items-grid {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
            gap: 20px;
        }
        .item-card {
            background: white;
            border-radius: 10px;
            overflow: hidden;
            box-shadow: 0 2px 8px rgba(0,0,0,0.1);
            transition: transform 0.3s, box-shadow 0.3s;
            cursor: pointer;
            height: 100%;
            display: flex;
            flex-direction: column;
        }
        .item-card:hover {
            transform: translateY(-5px);
            box-shadow: 0 5px 15px rgba(0,0,0,0.2);
        }
        .item-image {
            width: 100%;
            height: 200px;
            background-color: #f0f0f0;
            background-size: cover;
            background-position: center;
            background-repeat: no-repeat;
            position: relative;
        }
        .no-image {
            display: flex;
            align-items: center;
            justify-content: center;
            color: #888;
            font-size: 14px;
        }
        .item-info {
            padding: 15px;
            flex-grow: 1;
            display: flex;
            flex-direction: column;
        }
        .item-title {
            font-weight: bold;
            margin-bottom: 8px;
            font-size: 16px;
            display: -webkit-box;
            -webkit-line-clamp: 2;
            line-clamp: 2;
            -webkit-box-orient: vertical;
            overflow: hidden;
            text-overflow: ellipsis;
            line-height: 1.3;
            height: 2.6em;
        }
        .item-price {
            color: #e74c3c;
            font-size: 18px;
            font-weight: bold;
            margin-top: auto;
        }
        .item-meta {
            margin-top: 10px;
            font-size: 12px;
            color: #666;
            display: flex;
            justify-content: space-between;
        }
        .category-tag {
            background: #f0f0f0;
            padding: 3px 8px;
            border-radius: 10px;
            font-size: 11px;
        }
        .loading {
            text-align: center;
            padding: 30px;
            font-size: 18px;
            color: #666;
        }
        .no-results {
            text-align: center;
            padding: 40px 0;
            color: #666;
        }
        .banner {
            margin-bottom: 20px;
            border-radius: 10px;
            overflow: hidden;
            box-shadow: 0 2px 8px rgba(0,0,0,0.1);
        }
        .banner img {
            width: 100%;
            display: block;
        }
        .section-title {
            font-size: 22px;
            font-weight: bold;
            margin-bottom: 20px;
            color: #333;
            border-left: 4px solid #4a89dc;
            padding-left: 10px;
        }
        .filter-bar {
            display: flex;
            margin-bottom: 20px;
            background: white;
            padding: 15px;
            border-radius: 10px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.05);
        }
        .filter-item {
            margin-right: 20px;
            cursor: pointer;
            color: #666;
            transition: color 0.3s;
            position: relative;
        }
        .filter-item:hover, .filter-item.active {
            color: #4a89dc;
        }
        .filter-item.active:after {
            content: '';
            position: absolute;
            bottom: -5px;
            left: 0;
            width: 100%;
            height: 2px;
            background: #4a89dc;
        }
        @media (max-width: 768px) {
            .sidebar {
                display: none;
            }
            .main-content {
                margin-left: 0;
            }
            .items-grid {
                grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));
            }
        }
    </style>
</head>
<body>
<header class="header">
    <nav class="nav">
        <div class="logo">校园二手交易</div>
        <div class="search-bar">
            <input type="text" id="searchInput" placeholder="搜索商品...">
            <button id="searchButton" class="search-button">
                <i class="fas fa-search"></i> 搜索
            </button>
        </div>
        <div class="user-menu">
            <div class="user-avatar" onclick="showUserMenu()">
                <span id="userInitial">U</span>
            </div>
        </div>
    </nav>
</header>

<aside class="sidebar">
    <ul class="sidebar-menu">
        <li><a href="create-item.html">发布商品</a></li>
        <li><a href="favorites.html">我的收藏</a></li>
        <li><a href="my-items.html">我的商品</a></li>
        <li><a href="profile.html">个人中心</a></li>
        <li><a href="#" onclick="logout()">退出登录</a></li>
    </ul>
</aside>

<main class="main-content">
    <h2 class="section-title">商品分类</h2>
    <div class="filter-bar">
        <div class="filter-item active" data-category="all">全部</div>
        <div class="filter-item" data-category="ELECTRONICS">电子产品</div>
        <div class="filter-item" data-category="BOOKS">书籍</div>
        <div class="filter-item" data-category="CLOTHING">服饰鞋帽</div>
        <div class="filter-item" data-category="DAILY_SUPPLIES">生活用品</div>
        <div class="filter-item" data-category="OTHER">其他</div>
    </div>

    <h2 class="section-title">最新商品</h2>
    <div id="loadingIndicator" class="loading">加载中...</div>
    <div id="noResults" class="no-results" style="display:none;">没有找到相关商品</div>
    <div class="items-grid" id="itemsGrid">
        <!-- 商品卡片将通过JavaScript动态加载 -->
    </div>
</main>

<!-- <script src="https://kit.fontawesome.com/a076d05399.js" crossorigin="anonymous"></script> -->
<script>
    let currentUser = null;
    let allItems = []; // Stores the initial full list of items
    let searchResults = []; // Stores the items from the last search
    let isSearching = false; // Flag to indicate if currently displaying search results
    let currentCategory = 'all';

    // 检查登录状态
    function checkLogin() {
        const userData = localStorage.getItem('user');
        if (!userData) {
            window.location.href = 'login.html';
            return;
        }
        currentUser = JSON.parse(userData);
        document.getElementById('userInitial').textContent = currentUser.nickname ? currentUser.nickname.charAt(0).toUpperCase() : 'U';
    }

    // 加载商品列表
    async function loadItems(keyword = '', isSearch = false) {
        try {
            document.getElementById('loadingIndicator').style.display = 'block';
            document.getElementById('itemsGrid').innerHTML = '';
            document.getElementById('noResults').style.display = 'none';

            const url = keyword
                ? `/api/items/search?keyword=${encodeURIComponent(keyword)}`
                : '/api/items';

            const response = await fetch(url);
            if (!response.ok) {
                throw new Error(`HTTP error! status: ${response.status}`);
            }

            const items = await response.json();
            console.log(items); // Add this line

            if (!isSearch) {
                // If not a search, store the full list
                allItems = items;
                isSearching = false;
            } else {
                // If it's a search, store the results and set the flag
                searchResults = items;
                isSearching = true;
            }

            filterAndDisplayItems();

            document.getElementById('loadingIndicator').style.display = 'none';
        } catch (error) {
            console.error('加载商品失败:', error);
            document.getElementById('loadingIndicator').style.display = 'none';
            document.getElementById('noResults').textContent = '加载失败，请稍后再试';
            document.getElementById('noResults').style.display = 'block';
        }
    }

    // 过滤并显示商品
    function filterAndDisplayItems() {
        let itemsToFilter = isSearching ? searchResults : allItems;
        let filteredItems = itemsToFilter;

        if (currentCategory !== 'all') {
            filteredItems = itemsToFilter.filter(item => item.category === currentCategory);
        }

        if (filteredItems.length === 0) {
            document.getElementById('noResults').style.display = 'block';
            document.getElementById('itemsGrid').innerHTML = '';
            return;
        }

        document.getElementById('noResults').style.display = 'none';
        displayItems(filteredItems);
    }

    // 显示商品
    function displayItems(items) {
        const grid = document.getElementById('itemsGrid');
        grid.innerHTML = '';

        items.forEach(item => {
            const itemCard = document.createElement('div');
            itemCard.className = 'item-card';
            itemCard.onclick = () => viewItem(item.itemId);

            // 商品图片
            const itemImageDiv = document.createElement('div');
            itemImageDiv.className = 'item-image';

            // Use base64Image from the backend
            if (item.base64Image) {
                itemImageDiv.style.backgroundImage = `url(${item.base64Image})`;
                itemImageDiv.style.backgroundSize = 'cover';
                itemImageDiv.style.backgroundPosition = 'center';
                itemImageDiv.style.backgroundRepeat = 'no-repeat';
            } else {
                itemImageDiv.classList.add('no-image');
                itemImageDiv.innerHTML = '<span>暂无图片</span>';
            }

            // 商品信息
            const itemInfoDiv = document.createElement('div');
            itemInfoDiv.className = 'item-info';

            // 标题
            const titleP = document.createElement('p');
            titleP.className = 'item-title';
            titleP.textContent = item.title || '无标题';

            // 描述预览
            const descriptionDiv = document.createElement('div');
            descriptionDiv.style.fontSize = '13px';
            descriptionDiv.style.color = '#777';
            descriptionDiv.style.margin = '8px 0';
            descriptionDiv.style.display = '-webkit-box';
            descriptionDiv.style.webkitLineClamp = '2';
            descriptionDiv.style.webkitBoxOrient = 'vertical';
            descriptionDiv.style.overflow = 'hidden';
            descriptionDiv.style.textOverflow = 'ellipsis';
            descriptionDiv.style.lineHeight = '1.3';
            descriptionDiv.style.height = '2.6em';
            descriptionDiv.textContent = item.description || '暂无描述';

            // 价格
            const priceP = document.createElement('p');
            priceP.className = 'item-price';
            priceP.textContent = `¥ ${(item.price || 0).toFixed(2)}`;

            // 元数据
            const metaP = document.createElement('div');
            metaP.className = 'item-meta';

            const categorySpan = document.createElement('span');
            categorySpan.className = 'category-tag';
            categorySpan.textContent = item.category || '未分类';

            const viewsSpan = document.createElement('span');
            viewsSpan.textContent = `浏览: ${item.viewCount || 0}`;

            metaP.appendChild(categorySpan);
            metaP.appendChild(viewsSpan);

            // 组装商品卡片
            itemInfoDiv.appendChild(titleP);
            itemInfoDiv.appendChild(descriptionDiv);
            itemInfoDiv.appendChild(priceP);
            itemInfoDiv.appendChild(metaP);

            itemCard.appendChild(itemImageDiv);
            itemCard.appendChild(itemInfoDiv);

            grid.appendChild(itemCard);
        });
    }

    // 搜索功能
    function performSearch() {
        const keyword = document.getElementById('searchInput').value.trim();
        // Pass true to indicate it's a search
        loadItems(keyword, true);
    }

    // 分类过滤功能
    function setupCategoryFilter() {
        const filterItems = document.querySelectorAll('.filter-item');
        filterItems.forEach(item => {
            item.addEventListener('click', function() {
                // 移除所有active类
                filterItems.forEach(i => i.classList.remove('active'));
                // 添加active类到当前项
                this.classList.add('active');

                // 更新当前分类并重新过滤显示
                currentCategory = this.getAttribute('data-category');
                // Now filterAndDisplayItems will use the correct list (search results or all items)
                filterAndDisplayItems();
            });
        });
    }

    // 查看商品详情
    function viewItem(itemId) {
        window.location.href = `item-detail.html?id=${itemId}`;
    }

    // 显示用户菜单
    function showUserMenu() {
        window.location.href = 'profile.html';
    }

    // 退出登录
    function logout() {
        localStorage.removeItem('user');
        window.location.href = 'login.html';
    }

    // 事件监听器
    document.getElementById('searchButton').addEventListener('click', performSearch);
    document.getElementById('searchInput').addEventListener('keypress', function(e) {
        if (e.key === 'Enter') {
            performSearch();
        }
    });

    // 页面加载时执行
    document.addEventListener('DOMContentLoaded', () => {
        checkLogin();
        // Initial load of all items
        loadItems();

        // 处理搜索按钮点击
        document.getElementById('searchButton').addEventListener('click', () => {
            const keyword = document.getElementById('searchInput').value;
            loadItems(keyword, true);
        });

        // 处理搜索框回车
        document.getElementById('searchInput').addEventListener('keyup', (event) => {
            if (event.key === 'Enter') {
                const keyword = document.getElementById('searchInput').value;
                loadItems(keyword, true);
            }
        });

        // 处理分类筛选点击
        document.querySelectorAll('.filter-item').forEach(filter => {
            filter.addEventListener('click', () => {
                const category = filter.dataset.category;
                console.log(`--- [Debug] Category filter clicked. New category: "${category}" ---`);
                // 更新当前分类
                currentCategory = category;

                // 更新UI的active状态
                document.querySelector('.filter-item.active').classList.remove('active');
                filter.classList.add('active');

                // 重新过滤并显示商品
                filterAndDisplayItems();
            });
        });
    });
</script>
</body>
</html>